package com.yufeng.collaboration.service.impl;

import com.yufeng.collaboration.entity.Document;
import com.yufeng.collaboration.entity.DocumentMessage;
import com.yufeng.collaboration.mapper.DocumentMapper;
import com.yufeng.collaboration.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DocumentServiceImpl implements DocumentService {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private DocumentMapper documentMapper;


    @Override
    public List<Document> getDocumentsByGroupId(Integer groupId) {
        return documentMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Document>().eq("group_id", groupId));
    }

    @Override
    public Document getDocumentById(Integer id) {
        return documentMapper.selectById(id);
    }

    @Override
    public void createDocument(Document document) {
        documentMapper.insert(document);
    }

    @Override
    public void updateDocument(Document document) {
        documentMapper.updateById(document);
    }

    @Override
    public void deleteDocument(Integer id) {
        documentMapper.deleteById(id);
    }

    // 处理文档编辑消息，将消息广播给所有订阅该文档的客户端
    public void handleDocumentEdit(DocumentMessage message) {
        String destination = "/topic/document/" + message.getDocumentId();
        messagingTemplate.convertAndSend(destination, message);
    }
}